use arboard::{Clipboard, ImageData};
use image::DynamicImage;
use crate::types::TResult;

/// 保存图片到剪贴板
pub fn save_to_clipboard(img: &DynamicImage) -> TResult<()> {
    let mut clipboard = Clipboard::new()?;
    
    // 转换为RGBA格式
    let rgba_img = img.to_rgba8();
    let (width, height) = rgba_img.dimensions();
    
    // 创建ImageData
    let img_data = ImageData {
        width: width as usize,
        height: height as usize,
        bytes: rgba_img.into_raw().into(),
    };
    
    // 保存到剪贴板
    clipboard.set_image(img_data)?;
    
    Ok(())
}

/// 从剪贴板获取图片
pub fn get_from_clipboard() -> TResult<Option<DynamicImage>> {
    let mut clipboard = Clipboard::new()?;
    
    match clipboard.get_image() {
        Ok(img_data) => {
            // 从ImageData创建DynamicImage
            let img_buffer = image::ImageBuffer::from_raw(
                img_data.width as u32,
                img_data.height as u32,
                img_data.bytes.to_vec(),
            );
            
            if let Some(buffer) = img_buffer {
                let img = DynamicImage::ImageRgba8(buffer);
                Ok(Some(img))
            } else {
                Ok(None)
            }
        }
        Err(_) => Ok(None), // 剪贴板中没有图片或读取失败
    }
}